package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.YJbxx;
import cn.wizzer.app.bus.modules.models.YJbxxLcxx;
import cn.wizzer.app.bus.modules.models.YJbxxSfjl;
import cn.wizzer.app.bus.modules.services.YJbxxLcxxService;
import cn.wizzer.app.bus.modules.services.YJbxxService;
import cn.wizzer.app.bus.modules.services.YJbxxSfjlService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.ShiroUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 财务管理  虞秀斌  2019-11
 */
@IocBean
@At("/platform/bus/cwgl")
public class CwglController {
    private static final Log log = Logs.get();
    @Inject
    private YJbxxService yjbxxService;
    @Inject
    private YJbxxSfjlService yjbxxsfjlservice;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private ShiroUtil shiroUtil;
    @At("/?")
    @Ok("beetl:/platform/bus/cwgl/list.html")
    @RequiresPermissions(value = {"bus.cwgl.receivable","bus.cwgl.accepted"},logical = Logical.OR)
    public void index(String operation,HttpServletRequest req) {
        req.setAttribute("jylxMap", JSONObject.fromObject(sysDictService.getCodeMap("jylx")));
        String sfzt="";
        if(operation.equals("receivable")){
            sfzt="0,1";
        }
        else if(operation.equals("accepted")){
            sfzt="2";
        }
        req.setAttribute("sfzt",sfzt);
        req.setAttribute("operation",operation);
        req.setAttribute("userId",shiroUtil.getPrincipalProperty("id").toString());
        req.setAttribute("username",shiroUtil.getPrincipalProperty("username").toString());

    }

    @At
    @Ok("json:{locked:'password|salt',ignoreNull:false}")
    @RequiresPermissions("bus.rwgl")
    public Object data(@Param("searchKeyword") String searchKeyword,@Param("wtdw") String wtdw,@Param("sfzt") String sfzt, @Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            String sql ="select sfjl.id,jbxx.id as jbxxid,jbxx.sfzt,jbxx.ypbh,jbxx.ypmc,jbxx.sjdw,jbxx.wtdw,jbxx.jyks,ifnull(jbxx.jyfy,0) jyfy,sum(ifnull(sfjl.bcss,0)) as ysje,(jbxx.jyfy - sum(ifnull(sfjl.bcss,0)))as sjje " +
                    " from y_jbxx jbxx left join y_jbxx_sfjl sfjl on jbxx.id=sfjl.jbxxid and jbxx.delflag = 0 and sfjl.delflag=0 " +
                    " where 1=1 and jbxx.sfzt in ("+sfzt+") and jbxx.jyfy is not null and jbxx.jyfy <>''  ";
            if (Strings.isNotBlank(searchKeyword)) {
                sql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or jbxx.ypmc like '%"+searchKeyword+"%')";
            }
            if (Strings.isNotBlank(searchKeyword)) {
                sql+= " and jbxx.wtdw like '%"+wtdw+"%'";
            }
            sql+="group by jbxx.id  ";
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc,jbxx.opAt desc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc,jbxx.opAt desc ";
                }
            }else{
                sql+=" order by jbxx.opAt desc ";
            }
            return Result.success().addData(yjbxxService.listPage(pageNumber,pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            return Result.error();
        }
    }


    @At("/toReceivable/?")
    @Ok("json")
    @RequiresPermissions("bus.cwgl")
    public Object toReceivable(String jbxxid) {
        //YJbxx obj = yjbxxService.fetch(jbxxid);
        Cnd cnd = Cnd.NEW();
        cnd.and("jbxxId","=",jbxxid);
        cnd.and("delflag","=","0");
        String sql = "select jfrq,bcss,(select username from sys_user where id = a.opBy) as jfr,jffs,pzh,pjfl,pjhm from y_jbxx_sfjl a where jbxxId='"+jbxxid+"' and delflag = 0 ";
        List<Record> sfList = yjbxxsfjlservice.list(Sqls.create(sql));
        Map map = new HashMap();
        //map.put("obj","");
        map.put("sfList",JSONArray.fromObject(sfList));
        try {
            return Result.success().addData(map);
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.cwgl")
    @SLog(tag = "收费登记", msg = "样品:${args[0].ypbh}")
    public Object doReceivable(@Param("..") YJbxxSfjl obj) {
        try {
            YJbxx jbxx = yjbxxService.fetch(obj.getJbxxId());
            jbxx.setSfzt(obj.getSfzt());
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    yjbxxService.update(jbxx);
                    yjbxxsfjlservice.insert(obj);
                }
            });
            return Result.success("操作成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }
}
